<template>
  <div>
    <canvas ref="pdfCanvas"></canvas>
  </div>
</template>

<script setup>
import * as pdfjsLib from "pdfjs-dist";
// import pdfjsWorker from "pdfjs-dist/build/pdf.worker.mjs";
import { onMounted } from "vue";

const props = defineProps({
  pdfUrl: String,
});

onMounted(() => {
  loadPdf();
});

const loadPdf = async () => {
  // 设置 worker
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js';;

  // 加载 PDF 文件
  const loadingTask = pdfjsLib.getDocument(props.pdfUrl);
  try {
    const pdf = await loadingTask.promise;
    renderPdf(pdf);
  } catch (error) {
    console.error("Error loading PDF:", error);
  }
};

const renderPdf = async (pdf) =>{
  const pageNumber = 1; // 渲染第一页
      const page = await pdf.getPage(pageNumber);

      const scale = 1.5;
      const viewport = page.getViewport({ scale });

      const canvas = this.$refs.pdfCanvas;
      const context = canvas.getContext("2d");
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      const renderContext = {
        canvasContext: context,
        viewport: viewport,
      };

      await page.render(renderContext).promise;

}
</script>

<style scoped>
canvas {
  border: 1px solid #000;
}
</style>